<template>
  <el-dialog
    v-model="visible"
    title="推理详情"
    width="1200px"
    :close-on-click-modal="false"
    top="5vh"
  >
    <div v-loading="loading" class="detail-content" v-if="detailData">
      <!-- 基本信息 -->
      <div class="detail-section">
        <h3 class="section-heading">📌 基本信息</h3>
        <el-descriptions :column="3" border>
          <el-descriptions-item label="资产ID">
            {{ detailData.basic_info?.asset_id }}
          </el-descriptions-item>
          <el-descriptions-item label="IP地址">
            {{ detailData.basic_info?.ip }}
          </el-descriptions-item>
          <el-descriptions-item label="端口">
            {{ detailData.basic_info?.port }}
          </el-descriptions-item>
          <el-descriptions-item label="资产标题">
            {{ detailData.basic_info?.title }}
          </el-descriptions-item>
          <el-descriptions-item label="IP类型">
            {{ detailData.basic_info?.ip_type }}
          </el-descriptions-item>
          <el-descriptions-item label="ISP">
            {{ detailData.basic_info?.isp }}
          </el-descriptions-item>
          <el-descriptions-item label="任务ID">
            {{ detailData.basic_info?.task_id }}
          </el-descriptions-item>
          <el-descriptions-item label="任务名称">
            {{ detailData.basic_info?.task_name }}
          </el-descriptions-item>
          <el-descriptions-item label="发现时间">
            {{ detailData.basic_info?.discovered_at }}
          </el-descriptions-item>
          <el-descriptions-item label="推理时间">
            {{ detailData.basic_info?.inference_time }}
          </el-descriptions-item>
          <el-descriptions-item label="推理状态">
            <el-tag
              :type="getStatusType(detailData.basic_info?.status)"
              size="small"
            >
              {{ detailData.basic_info?.status_display }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="推理模式">
            {{ detailData.basic_info?.inference_mode_display }}
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 推理结果 -->
      <div class="detail-section" v-if="detailData.inference_result">
        <h3 class="section-heading">🎯 推理结果</h3>
        <div class="overall-score">
          <div class="score-label">综合得分</div>
          <div class="score-value">
            {{ detailData.inference_result.overall_score }}
          </div>
        </div>
        <el-table
          :data="detailData.inference_result.top3_departments"
          border
          style="margin-top: 15px"
        >
          <el-table-column prop="rank" label="排名" width="80" align="center" />
          <el-table-column
            prop="department_name"
            label="部门名称"
            min-width="250"
          />
          <el-table-column label="置信度" width="120" align="center">
            <template #default="{ row }">
              <span class="confidence-value">{{ row.confidence }}%</span>
            </template>
          </el-table-column>
          <el-table-column label="匹配原因" min-width="300">
            <template #default="{ row }">
              <el-tag
                v-for="(reason, index) in row.match_reasons"
                :key="index"
                size="small"
                style="margin-right: 8px; margin-bottom: 4px"
              >
                {{ reason }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 规则引擎 -->
      <div class="detail-section" v-if="detailData.rule_engine">
        <h3 class="section-heading">⚙️ 规则引擎</h3>
        <div class="engine-summary">
          <span>权重: {{ detailData.rule_engine.weight }}%</span>
          <span>得分: {{ detailData.rule_engine.score }}</span>
        </div>
        <el-table
          :data="detailData.rule_engine.dimensions"
          border
          style="margin-top: 15px"
        >
          <el-table-column label="维度" min-width="150">
            <template #default="{ row }">
              <div class="dimension-name">
                <i
                  :class="row.matched ? 'el-icon-check' : 'el-icon-close'"
                  :style="{
                    color: row.matched ? '#67c23a' : '#909399',
                    marginRight: '8px',
                  }"
                ></i>
                {{ row.name }}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="score"
            label="得分"
            width="100"
            align="center"
          />
          <el-table-column
            prop="weight"
            label="权重"
            width="100"
            align="center"
          />
          <el-table-column label="详情" min-width="400">
            <template #default="{ row }">
              <div class="dimension-details">{{ row.details }}</div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- AI特征 -->
      <div class="detail-section" v-if="detailData.ai_features">
        <h3 class="section-heading">🤖 AI特征</h3>
        <div class="ai-summary">
          <span>权重: {{ detailData.ai_features.weight }}%</span>
          <span>得分: {{ detailData.ai_features.score }}</span>
        </div>
        <div class="features-grid">
          <div
            v-for="feature in detailData.ai_features.features"
            :key="feature.id"
            class="feature-item"
          >
            <div class="feature-name">{{ feature.name }}</div>
            <div class="feature-value">{{ feature.value }}</div>
          </div>
        </div>
      </div>

      <!-- 历史记录 -->
      <div
        class="detail-section"
        v-if="detailData.history && detailData.history.length > 0"
      >
        <h3 class="section-heading">📝 历史记录</h3>
        <el-timeline>
          <el-timeline-item
            v-for="(item, index) in detailData.history"
            :key="index"
            :timestamp="item.time"
            placement="top"
          >
            <div class="history-item">
              <div class="history-action">{{ item.action }}</div>
              <div class="history-operator">操作人: {{ item.operator }}</div>
              <div class="history-result">{{ item.result }}</div>
            </div>
          </el-timeline-item>
        </el-timeline>
      </div>
    </div>

    <template #footer>
      <el-button @click="handleCancel">关闭</el-button>
      <el-button
        type="info"
        @click="handleViewProfileGraph"
        :disabled="!props.assetId"
      >
        查看资产画像
      </el-button>
      <el-button
        v-if="canSubmitFeedback"
        type="success"
        @click="handleOpenFeedback"
      >
        提交反馈
      </el-button>
      <el-button
        v-if="canUpdateDepartment"
        type="warning"
        @click="handleOpenUpdateDepartment"
      >
        修改部门
      </el-button>
      <el-button
        type="primary"
        :loading="exportLoading"
        @click="handleExport"
        :disabled="!detailData"
      >
        导出详情
      </el-button>
    </template>

    <!-- 用户反馈弹窗 -->
    <FeedbackModal
      v-model="feedbackVisible"
      :asset-id="props.assetId"
      :top-departments="topDepartments"
      @success="handleFeedbackSuccess"
    />

    <!-- 修改部门归属弹窗 -->
    <UpdateDepartmentModal
      v-model="updateDepartmentVisible"
      :asset-id="props.assetId"
      :current-department="currentDepartment"
      @success="handleUpdateDepartmentSuccess"
    />
  </el-dialog>
</template>

<script setup lang="ts">
import { computed, ref, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { getInferenceDetail, exportInferenceDetail } from "../../../servers";
import FeedbackModal from "./FeedbackModal.vue";
import UpdateDepartmentModal from "./UpdateDepartmentModal.vue";

const props = defineProps({
  modelValue: { type: Boolean, default: false },
  assetId: { type: Number, default: null },
});

const emit = defineEmits<{
  (e: "update:modelValue", value: boolean): void;
}>();

const route = useRoute();
const router = useRouter();

const visible = computed({
  get: () => props.modelValue,
  set: (value: boolean) => emit("update:modelValue", value),
});

const loading = ref(false);
const exportLoading = ref(false);
const detailData = ref<any>(null);
const feedbackVisible = ref(false);
const updateDepartmentVisible = ref(false);

// 是否可以提交反馈（已推理状态）
const canSubmitFeedback = computed(() => {
  const status = detailData.value?.basic_info?.status;
  return status && status !== "pending";
});

// 是否可以修改部门（已确认状态）
const canUpdateDepartment = computed(() => {
  const status = detailData.value?.basic_info?.status;
  return status === "confirmed";
});

// 获取TOP3部门列表（用于反馈）
const topDepartments = computed(() => {
  return detailData.value?.inference_result?.top3_departments || [];
});

// 获取当前部门（用于修改部门）
const currentDepartment = computed(() => {
  const top1 = detailData.value?.inference_result?.top3_departments?.[0];
  return top1
    ? {
        id: top1.department_id,
        name: top1.department_name,
      }
    : null;
});

// 监听弹窗打开，获取详情
watch(visible, async (newVal) => {
  if (newVal && props.assetId) {
    await fetchDetail();
  } else if (!newVal) {
    detailData.value = null;
  }
});

// 监听 assetId 变化
watch(
  () => props.assetId,
  async (newId) => {
    if (newId && visible.value) {
      await fetchDetail();
    }
  }
);

// 获取推理详情
const fetchDetail = async () => {
  if (!props.assetId) return;

  loading.value = true;
  try {
    const { data } = await getInferenceDetail(props.assetId);
    if (data) {
      detailData.value = data;
    }
  } catch (error: any) {
    ElMessage.error(error?.message || "获取推理详情失败");
  } finally {
    loading.value = false;
  }
};

// 导出详情
const handleExport = async () => {
  if (!props.assetId) {
    ElMessage.warning("资产ID不存在");
    return;
  }

  exportLoading.value = true;
  try {
    const blob = await exportInferenceDetail(props.assetId, {
      format: "pdf",
      include_sections: [
        "basic_info",
        "inference_result",
        "rule_engine",
        "ai_features",
        "history",
      ],
    });

    // 创建下载链接
    const url = URL.createObjectURL(blob as any);
    const a = document.createElement("a");
    a.href = url;
    const date = new Date().toISOString().split("T")[0].replace(/-/g, "");
    const ip = detailData.value?.basic_info?.ip || "unknown";
    const port = detailData.value?.basic_info?.port || "";
    a.download = `推理详情_${ip}_${port}_${date}.pdf`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);

    ElMessage.success("导出成功");
  } catch (error: any) {
    ElMessage.error(error?.message || "导出失败");
  } finally {
    exportLoading.value = false;
  }
};

// 获取状态标签类型
const getStatusType = (
  status: string
): "success" | "warning" | "danger" | "info" => {
  const typeMap: Record<string, "success" | "warning" | "danger" | "info"> = {
    pending: "info",
    inferred: "warning",
    confirmed: "success",
    rejected: "danger",
    whitelisted: "success",
  };
  return typeMap[status] || "info";
};

// 打开反馈弹窗
const handleOpenFeedback = () => {
  feedbackVisible.value = true;
};

// 打开修改部门弹窗
const handleOpenUpdateDepartment = () => {
  updateDepartmentVisible.value = true;
};

// 反馈成功
const handleFeedbackSuccess = () => {
  // 刷新详情
  fetchDetail();
};

// 修改部门成功
const handleUpdateDepartmentSuccess = () => {
  // 刷新详情
  fetchDetail();
};

// 查看资产画像图谱
const handleViewProfileGraph = () => {
  if (!props.assetId) {
    ElMessage.warning("资产ID不存在");
    return;
  }

  // 关闭详情弹窗
  emit("update:modelValue", false);

  // 跳转到资产画像图谱页
  router.push({
    name: "assetProfileGraph",
    params: {
      asset_id: props.assetId,
    },
  });
};

// 取消
const handleCancel = () => {
  emit("update:modelValue", false);
};
</script>

<style scoped lang="scss">
.detail-content {
  max-height: 70vh;
  overflow-y: auto;
  padding-right: 10px;
}

.detail-section {
  margin-bottom: 30px;

  &:last-child {
    margin-bottom: 0;
  }
}

.section-heading {
  font-size: 16px;
  font-weight: 500;
  margin: 0 0 15px 0;
  color: #303133;
  display: flex;
  align-items: center;
  gap: 8px;
}

.overall-score {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 15px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 8px;
  color: white;

  .score-label {
    font-size: 16px;
    font-weight: 500;
  }

  .score-value {
    font-size: 32px;
    font-weight: bold;
  }
}

.engine-summary,
.ai-summary {
  display: flex;
  gap: 20px;
  margin-bottom: 15px;
  font-size: 14px;
  color: #606266;

  span {
    font-weight: 500;
  }
}

.confidence-value {
  font-weight: 500;
  color: #409eff;
  font-size: 16px;
}

.dimension-name {
  display: flex;
  align-items: center;
  font-weight: 500;
}

.dimension-details {
  font-size: 13px;
  color: #606266;
  white-space: pre-line;
  line-height: 1.6;
}

.features-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 12px;
  margin-top: 15px;

  .feature-item {
    padding: 12px;
    background-color: #f5f7fa;
    border-radius: 4px;
    border: 1px solid #ebeef5;

    .feature-name {
      font-size: 13px;
      color: #909399;
      margin-bottom: 6px;
    }

    .feature-value {
      font-size: 14px;
      color: #303133;
      font-weight: 500;
    }
  }
}

.history-item {
  .history-action {
    font-weight: 500;
    color: #303133;
    margin-bottom: 4px;
  }

  .history-operator {
    font-size: 12px;
    color: #909399;
    margin-bottom: 4px;
  }

  .history-result {
    font-size: 13px;
    color: #606266;
  }
}
</style>
